# main building script for BeCJK

# path for library and BeCJK & dicts
besavager_path = './generated/lib/besavager'
becjk_addon = './generated/add-ons/input_server/methods/BeCJK'
dicts_path = './generated/data/BeCJK/dicts'

env = Environment()
Export("env")


# besavager install
besavager_script = '#besavager/SConscript'
besavager_files= SConscript(besavager_script, variant_dir = 'build/besavager')
env.Install(besavager_path, besavager_files);

# becjk install
becjk_script = '#src/SConscript'
becjk_file = SConscript(becjk_script, variant_dir='build/BeCJK')
env.InstallAs(becjk_addon, becjk_file)

# dicts install
dicts_script = '#data/dicts/SConscript'
dicts_files = SConscript(dicts_script, variant_dir='build/dicts')
env.Install(dicts_path, dicts_files)

# Create hpkg package
def create_hpkg(target, source, env):
    import os
    import subprocess
    
    # 确保生成目录存在
    os.makedirs('generated', exist_ok=True)
    
    # 使用subprocess运行package命令，这样可以更好地处理错误
    try:
        result = subprocess.run(['package', 'create', '-b', 'generated', 'BeCJK-1.0.0~beta2-x86_64.hpkg'],
                               check=True,
                               capture_output=True,
                               text=True)
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error creating package: {e.stderr}")
        return 1
    except Exception as e:
        print(f"Unexpected error: {str(e)}")
        return 1
    
    return None

# 添加打包命令，依赖于所有安装目标
env.Command('BeCJK-1.0.0~beta2-x86_64.hpkg',
           [besavager_path, becjk_addon, dicts_path],
           create_hpkg)

# 添加package别名命令
env.Alias('package', ['BeCJK-1.0.0~beta2-x86_64.hpkg'])

